<template>
    <div class="app-container">
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="车牌号码" prop="plateNumber">
          <el-input
            v-model="queryParams.plateNumber"
            placeholder="请输入车牌号码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="黑名单状态" clearable size="small">
            <el-option label="生效" value="0" />
            <el-option label="失效" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="dateRange"
            size="small"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['vehicle:blacklist:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['vehicle:blacklist:remove']"
          >删除</el-button>
        </el-col>
      </el-row>
  
      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="blacklistList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="blacklistId" />
        <el-table-column label="车牌号码" align="center" prop="plateNumber" />
        <el-table-column label="加入原因" align="center" prop="reason" :show-overflow-tooltip="true"/>
        <el-table-column label="生效时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="失效时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['vehicle:blacklist:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['vehicle:blacklist:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页区域 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改黑名单对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="车牌号码" prop="plateNumber">
            <el-input v-model="form.plateNumber" placeholder="请输入车牌号码" />
          </el-form-item>
          <el-form-item label="加入原因" prop="reason">
            <el-input v-model="form.reason" type="textarea" placeholder="请输入加入原因" />
          </el-form-item>
          <el-form-item label="有效期" prop="dateRange">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio label="0">生效</el-radio>
              <el-radio label="1">失效</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
import { listBlacklist, getBlacklist, addBlacklist, updateBlacklist, delBlacklist, changeStatus } from "@/api/Vehicle/blacklist";

  
  export default {
    name: "Blacklist",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 黑名单表格数据
        blacklistList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          plateNumber: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        // 日期选择器选项
        pickerOptions: {
          shortcuts: [{
            text: '一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime());
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime());
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime());
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }],
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
          }
        },
        // 表单校验
        rules: {
          plateNumber: [
            { required: true, message: "车牌号码不能为空", trigger: "blur" },
            { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/, message: "请输入正确的车牌号码", trigger: "blur" }
          ],
          reason: [
            { required: true, message: "加入原因不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询黑名单列表 */
      getList() {
        this.loading = true;
        listBlacklist(this.addDateRange(this.queryParams, this.dateRange)).then(
          response => {
            this.blacklistList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加黑名单车辆";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const blacklistId = row.blacklistId || this.ids;
        getBlacklist(blacklistId).then(response => {
          this.form = response.data;
          this.dateRange = [this.form.startTime, this.form.endTime];
          this.open = true;
          this.title = "修改黑名单车辆";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (!this.dateRange || this.dateRange.length !== 2) {
              this.$message.error("请选择有效期");
              return;
            }
            
            this.form.startTime = this.dateRange[0];
            this.form.endTime = this.dateRange[1];
            
            // 验证时间范围
            if (new Date(this.form.startTime) >= new Date(this.form.endTime)) {
              this.$message.error("结束时间必须大于开始时间");
              return;
            }
            
            if (this.form.blacklistId != null) {
              updateBlacklist(this.form).then(response => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBlacklist(this.form).then(response => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const blacklistIds = row.blacklistId || this.ids;
        this.$confirm('是否确认删除黑名单编号为"' + blacklistIds + '"的数据项？', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return delBlacklist(blacklistIds);
        }).then(() => {
          this.getList();
          this.$message.success("删除成功");
        }).catch((error) => {
          console.error('删除失败:', error);
          this.$message.error("删除失败");
        });
      },
      /** 状态修改 */
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$confirm('确认要"' + text + '""' + row.plateNumber + '"的黑名单状态吗？', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return changeStatus(row.blacklistId, row.status);
        }).then(() => {
          this.$message.success(text + "成功");
        }).catch(() => {
          row.status = row.status === "0" ? "1" : "0";
          this.$message.error("操作已取消");
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.blacklistId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 重置表单数据 */
      reset() {
        this.form = {
          blacklistId: null,
          plateNumber: null,
          reason: null,
          status: "0",
          remark: null
        };
        this.dateRange = [];
        this.resetForm("form");
      },
      /** 取消按钮 */
      cancel() {
        this.open = false;
        this.reset();
      }
    }
  };
  </script>
  
  <style scoped>
  .el-table .warning-row {
    background: oldlace;
  }
  .el-table .success-row {
    background: #f0f9eb;
  }
  </style>